package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ApFollowBehaviorMapper;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApFollowBehaviorService;
import com.heima.common.exception.CustomException;
import com.heima.model.behavior.dtos.FollowBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApFollowBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @作者 itcast
 * @创建日期 2021/4/22 9:47
 **/
@Service
@Slf4j
public class ApFollowBehaviorServiceImpl extends ServiceImpl<ApFollowBehaviorMapper, ApFollowBehavior> implements ApFollowBehaviorService {
    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;

    @Override
    public ResponseResult saveFollowBehavior(FollowBehaviorDto dto) {
        // 1. 查询行为实体数据
        ApBehaviorEntry behaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(dto.getUserId(), null);
        if (behaviorEntry == null) {
            log.info("记录关注行为实体失败, 未查询到行为实体数据 userId : {}",dto.getUserId());
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"对应的行为实体数据不存在");
        }
        // 2. 封装关注行为实体数据
        ApFollowBehavior followBehavior = getOne(Wrappers.<ApFollowBehavior>lambdaQuery().eq(ApFollowBehavior::getEntryId, behaviorEntry.getId()).eq(ApFollowBehavior::getFollowId, dto.getFollowId()));
        if (followBehavior != null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"已经关注过该作者");
        }
        // 保存关注行为
        followBehavior = new ApFollowBehavior();
        followBehavior.setEntryId(behaviorEntry.getId());
        followBehavior.setArticleId(dto.getArticleId());
        followBehavior.setFollowId(dto.getFollowId());
        followBehavior.setCreatedTime(new Date());
        save(followBehavior);
        // 3. 保存
        return ResponseResult.okResult();
    }
}
